package top.codef.secure.components;

import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.InvalidSessionStrategy;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import top.codef.secure.pojomodel.SecureResponseEnum;
import top.codef.secure.properties.enums.InvalidateSessionHandle;

public class CerberusSessionInvalidateStratergy implements InvalidSessionStrategy {

	private final InvalidateSessionHandle invalidateSessionHandle;

	private String redirectUrl = "/";

	private final ObjectMapper objectMapper;

	private final String CONTENT_TYPE = "application/json; charset=utf-8";

	public CerberusSessionInvalidateStratergy(InvalidateSessionHandle invalidateSessionHandle, String redirectUrl,
			ObjectMapper objectMapper) {
		this.invalidateSessionHandle = invalidateSessionHandle;
		this.redirectUrl = redirectUrl;
		this.objectMapper = objectMapper;
	}

	@Override
	public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpSession session = request.getSession(false);
		if (session != null)
			session.invalidate();
		switch (invalidateSessionHandle) {
		case NO_HANDLE:
			return;
		case AUTH_FAILED:
			response.setContentType(CONTENT_TYPE);
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			response.getWriter().write(
					objectMapper.writeValueAsString(SecureResponseEnum.AUTH_FAIL.createSecureModel("用户验证异常，请重新登录")));
			return;
		case FORBIDDEN:
			response.setContentType(CONTENT_TYPE);
			response.setStatus(HttpStatus.FORBIDDEN.value());
			response.getWriter().write(
					objectMapper.writeValueAsString(SecureResponseEnum.AUTH_FAIL.createSecureModel("用户验证异常，请重新登录")));
			return;
		case REDIRECT:
			response.sendRedirect(redirectUrl);
			return;
		}
	}
}
